package cn.anc.aonicardv.module.ui.recorder;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import cn.anc.aonicardv.Configs;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.RecorderConnectListBean;
import cn.anc.aonicardv.event.RequestMobileNetworkEvent;
import cn.anc.aonicardv.event.ScreenDisplayEvent;
import cn.anc.aonicardv.event.UpdateWifiName;
import cn.anc.aonicardv.module.ui.base.BaseFragment;
import cn.anc.aonicardv.module.ui.my.SettingActivity;
import cn.anc.aonicardv.param.ParamManager;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.AoniRecorderInfoUtils;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.FileUtils;
import cn.anc.aonicardv.util.NetUtils;
import cn.anc.aonicardv.util.SpUtils;
import cn.anc.aonicardv.util.StringUtils;
import cn.anc.aonicardv.util.UIUtil;
import cn.anc.aonicardv.util.WiFiUtil;
import cn.anc.aonicardv.util.ui.CarSettingGuiHandler;
import cn.anc.aonicardv.util.ui.IpUtil;
import cn.anc.aonicardv.widget.ConnectRecorderWifiDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;
import cn.anc.httpcontrolutil.CarControlSettings;
import cn.anc.httpcontrolutil.SocketUtils;

import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
import static android.net.NetworkCapabilities.TRANSPORT_WIFI;


/**
 * Created by yangdai on 2017/5/16.
 */

public class RecorderFragment extends BaseFragment implements CarControl.OnHeartBeatCallBack, View.OnClickListener, CarControl.OnCarControlCallback {

    public static final String TYPE_NORMAL = "type_normal";
    public static final String TYPE_EVENT = "type_event";
    @BindView(R2.id.tv_enter_recorder)
    TextView enterRecorderTv;
    @BindView(R2.id.tv_connect_wifi_name)
    TextView connectWifiNameTv;
    @BindView(R2.id.tv_connect_wifi_name_hint)
    TextView connectWifiNameTvHint;


    @BindView(R2.id.tv_title)
    TextView titleTv;
    @BindView(R2.id.tv_right_image)
    ImageView rightTv;
    @BindView(R2.id.tv_progress)
    TextView progressTv;
    @BindView(R2.id.tv_big_product_image)
    TextView bigProductImageTv;
    private boolean isConnecting;
    private boolean isPause;
    private ConnectivityManager connectivityManager;
    //因为在mainActivity界面监听wifi，只要onResume就会获取一次。增加一个变量控制当当前ssid一致时，不自动进入
    private String currentSSID;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(R.layout.fragment_recorder);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

    }

    @Override
    public void initVariable() {
        connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        dialogUtils = new DialogUtils();
    }

    private boolean isTimeOut = false;
    private final int MSG_CONNECT_TIME_OUT = 522;
    private final int MSG_CONNECT_ERROR = 525;
    private final int MSG_GET_DEVICE_INFO_ERROR = 527;
    private int timeOutCode = 0;
    private int timeOut = 0;
    private Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CONNECT_TIME_OUT:
                    timeOut++;
                    //设置超时时间为5秒
                    if (isConnecting && timeOut >= 10) {
                        isTimeOut = true;
                        stopConnectAnimation();
                        String timeOutToast = UIUtil.getString(R.string.recorder_album_open_failed_hint) + ":" + timeOutCode;
                        Toast.makeText(getActivity(), timeOutToast, Toast.LENGTH_SHORT).show();
                    } else {
                        sendEmptyMessageDelayed(MSG_CONNECT_TIME_OUT, 1000);
                    }
                    break;

                case MSG_CONNECT_ERROR:
                    stopConnectAnimation();
                    String errorMsg = (String) msg.obj;
                    String errorToast = UIUtil.getString(R.string.tip_cardv_connect_fail) + ":" + errorMsg;
                    Toast.makeText(getActivity(), errorToast, Toast.LENGTH_SHORT).show();
                    break;

                case MSG_GET_DEVICE_INFO_ERROR:
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (connectParam == Constant.ConnectParam.GETDEVICEINFO) {
                                doGetDeviceInfo();
                            } else if (connectParam == Constant.ConnectParam.GETDEVICEPASSWORD) {
                                doGetWifiPassword();
                            } else {
                                doGetAllSettings();
                            }
                        }
                    }, 500);

                    break;
                default:
                    break;
            }

            super.handleMessage(msg);
        }
    };

    @Override
    public void findViewById(View view) {
    }

    @Override
    public void setListener() {
        UIUtil.setProductDefaultImage(Configs.DEFUTL_SHOW_IMAGE, bigProductImageTv);
        enterRecorderTv.setOnClickListener(this);
        rightTv.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        CarControl.setOnHeartBeatCallBack(this);
        updateRecorderConnectStatus();
        if (!CarControl.IsConnected.get())
            enterRecorderTv.setText(getString(R.string.connect_recorder));
        else
            enterRecorderTv.setText(getString(R.string.enter_recorder));
        isPause = false;
        setProductImageByModel();
        if (MyApplication.needAutoConnect) {
            connectCurrentWifiFromRecorderList();
        }

    }

    private ProgressDialog progressDialog;

    private void initProgressDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setIndeterminate(false);//循环滚动
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("loading...");
        progressDialog.setCancelable(false);//false不能取消显示，true可以取消显示
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true;
    }

    private void updateRecorderConnectStatus() {
        setCurrentWifiName();
        if (CarControl.IsConnected.get()) {
            connectWifiNameTvHint.setVisibility(View.GONE);

            connectWifiNameTv.setTextColor(getResources().getColor(R.color.custom_progress));
            Drawable drawable = getResources().getDrawable(R.mipmap.connected_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            connectWifiNameTv.setCompoundDrawables(null, null, drawable, null);
        } else {
            connectWifiNameTvHint.setVisibility(View.VISIBLE);
            connectWifiNameTvHint.setTextColor(Color.RED);
            connectWifiNameTv.setTextColor(Color.RED);
            Drawable drawable = getResources().getDrawable(R.mipmap.no_connect_icon);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            connectWifiNameTv.setCompoundDrawables(null, null, drawable, null);
        }
    }

    @Override
    public void initData() {
        titleTv.setText(getString(R.string.recorder));
        rightTv.setVisibility(View.VISIBLE);
        rightTv.setImageResource(R.mipmap.record_settings);

    }

    private void setProductImageByModel() {
        String temp = SpUtils.getString(Constant.SpKeyParam.RECORDER_CONNECT_LIST, null);
        if (temp != null) {
            List<RecorderConnectListBean> recorderConnectListBeanList = new Gson().fromJson(temp, new TypeToken<List<RecorderConnectListBean>>() {
            }.getType());
            for (int i = 0; i < recorderConnectListBeanList.size(); i++) {
                if (recorderConnectListBeanList.get(i).isLast()) {
                    recorderConnectListBeanList.get(i).setProductImage(bigProductImageTv, true);
                }
            }
        }
    }


    private void connectCurrentWifiFromRecorderList() {
        //这里做一个判断  自动连接判断
        if (!getConnectStatus() || isConnecting || CarControl.IsConnected.get()) {
            return;
        }
        if (null == currentSSID || !currentSSID.equals(MyApplication.wifiSSID)) {
            if (!isPause && !isConnecting) {
                isConnecting = true;
                MyApplication.needAutoConnect = false;
                currentSSID = MyApplication.wifiSSID;
                enterRecorder();
                requestNetwork();
            }
        }

    }

    private void requestNetwork() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            checkNetworkAvailable();
            forceSendRequestByMobileData();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        updateRecorderConnectStatus();
    }

    /**
     * 判断是wifi直连返回值   并做出相对应处理，四种情况
     * <p>
     * 1.当传统wifi未连接，wifi直连连接。使用wifi直连
     * 2.当传统wifi连接，wifi直连未连接  使用传统wifi
     * 3.当传统wifi连接其他非记录仪ip wifi，wifi直连连接记录仪，使用wifi直连
     * 4.当传统wifi连接记录仪，wifi直连也连接记录仪时，使用传统wifi记录仪
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateWifiName event) {
        String wifiIp = IpUtil.getContainsIp(NetUtils.getWifiIpAddress(getContext()));
        //获取当前手机wifi，当手机传统wifi获取到的ip为记录仪Ip时，只使用传统记录仪wifi
        if (!StringUtils.isEmptyOrNull(wifiIp)) {
            if (!event.isWifiP2P) {
                if (null != connectRecorderWifiDialog && connectRecorderWifiDialog.isShowing()) {
                    connectRecorderWifiDialog.dismiss();
                }
                MyApplication.wifiSSID = event.devicesName;
                MyApplication.IPHeader = IpUtil.getContainsIp(event.deviceIp);
                MyApplication.IP = IpUtil.getContainsIp(event.deviceIp) + "1";
                CarControl.setParam(MyApplication.IP, ParamManager.CarServerParam.CarControlHttpPort);
                CarControl.setDataParam(MyApplication.IP, ParamManager.CarServerParam.CarControlDataPort);
                updateRecorderConnectStatus();
                if (event.isReceiver) {
                    currentSSID = null;
                    if (!isPause)
                        connectCurrentWifiFromRecorderList();
                } else {
                    connectCurrentWifiFromRecorderList();
                }

            }
        } else {
            if (event.isWifiP2P) {
                MyApplication.wifiSSID = event.devicesName;
                MyApplication.IPHeader = IpUtil.getContainsIp(event.deviceIp);
                MyApplication.IP = IpUtil.getContainsIp(event.deviceIp) + "1";
                CarControl.setParam(MyApplication.IP, ParamManager.CarServerParam.CarControlHttpPort);
                CarControl.setDataParam(MyApplication.IP, ParamManager.CarServerParam.CarControlDataPort);
            }
        }

    }

    private ConnectRecorderWifiDialog connectRecorderWifiDialog;

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_enter_recorder) {
            if (!getConnectStatus()) {
                connectRecorderWifiDialog = new ConnectRecorderWifiDialog(getContext(), R.style.BaseDialogStyle);
                connectRecorderWifiDialog.show();
            } else {
                if (!isConnecting) {
                    isConnecting = true;
                    requestNetwork();
                    enterRecorder();
                }
            }
        } else if (i == R.id.tv_right_image) {
            ActivityUtils.jumpActivity(getActivity(), SettingActivity.class);
        }
    }

    private DialogUtils dialogUtils;
    private int connectParam = Constant.ConnectParam.GETDEVICEINFO;

    private void showGpsDialog() {
        dialogUtils.getCustomMessageAlertDialog(getActivity(), R.string.location_authorization_alert).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton(getString(R.string.discount), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
            }
        }).show();
    }

    //判断是否可以连接   ---连接必然条件  ssid不能为空，ssid相对应的开头   IPHeader不能为空  ip不能为空
    private boolean getConnectStatus() {
        boolean checkWifi = WiFiUtil.getInstance(getContext()).isConnected(MyApplication.wifiSSID);
        writeFile("wifi isConnected:" + checkWifi + "\n");
        return MyApplication.IP != null && MyApplication.IPHeader != null && MyApplication.wifiSSID != null && WiFiUtil.getInstance(getContext()).isConnected(MyApplication.wifiSSID) && MyApplication.wifiSSID.toLowerCase().startsWith("lynk&co-s1a-") && NetUtils.getWifiIpAddress(getContext()).startsWith(MyApplication.IPHeader);

    }


//    private boolean getConnectStatus() {
//        boolean checkWifi = WiFiUtil.getInstance(getContext()).isConnected(MyApplication.wifiSSID);
//        writeFile("wifi isConnected:" + checkWifi + "\n");
//        return MyApplication.IP != null && MyApplication.IPHeader != null && MyApplication.wifiSSID != null && WiFiUtil.getInstance(getContext()).isConnected(MyApplication.wifiSSID) && NetUtils.getWifiIpAddress(getContext()).startsWith(MyApplication.IPHeader);
//
//    }

    private void writeFile(String sb) {
        try {
            String fileName = "crash-lingke.log";
            if (FileUtils.hasSdcard()) {
                String path = getGlobalpath();
                File dir = new File(path);
                if (!dir.exists())
                    dir.mkdirs();

                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.getBytes());
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
        }
    }

    public static String getGlobalpath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "crash" + File.separator;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RequestMobileNetworkEvent event) {
        forceSendRequestByMobileData();
    }

    private void setCurrentWifiName() {
        connectWifiNameTv.setText("");
        if (MyApplication.IPHeader != null && MyApplication.wifiSSID != null
                && CarControl.IsConnected.get()
        ) {
            connectWifiNameTv.setText(MyApplication.wifiSSID);
        } else {
            connectWifiNameTv.setText(R.string.recorder_no_connect_hint);
        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
        connectParam = Constant.ConnectParam.GETDEVICEINFO;
        doGetDeviceInfo();
    }


    private void setConnectBtnEnable(boolean enable) {
        if (null != enterRecorderTv) {
            if (enable) {
                enterRecorderTv.setEnabled(true);
            } else {
                enterRecorderTv.setEnabled(false);
            }
        }

    }

    @Override
    public void OnHeartBeatConnectFail() {
        if (isConnecting) {
            Message msg = new Message();
            msg.what = MSG_CONNECT_ERROR;
            msg.obj = "400";
            handler.sendMessage(msg);
        }

    }

    @Override
    public void OnHeartBeatDisconnect() {
    }


    private void startConnectAnimation() {
        isTimeOut = false;
        timeOut = 0;
        handler.sendEmptyMessage(MSG_CONNECT_TIME_OUT);
        handler.post(new Runnable() {
            @Override
            public void run() {
                setConnectBtnEnable(false);
                progressTv.setVisibility(View.VISIBLE);
                progressTv.clearAnimation();
                Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.recorder_connect_progress);
                progressTv.startAnimation(animation);
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != handler) {
            handler.removeMessages(MSG_CONNECT_TIME_OUT);
        }
        currentSSID = null;
        EventBus.getDefault().unregister(this);
    }
    private void doGetDeviceInfo() {
        timeOutCode = 501;
        CarControl.doGetDeviceInfo(this);
    }

    private void doGetWifiPassword() {
        timeOutCode = 502;
        CarControl.doGetWifiPassword(this);
    }

    private void doGetAllSettings() {
        timeOutCode = 503;
        CarControl.doGetAllSettings(this);
    }

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        if (code != 0) {
            if (isConnecting) {
                handler.sendEmptyMessage(MSG_GET_DEVICE_INFO_ERROR);
            }
            return;
        }
        switch (info.msg_id) {
            case CarControlCommand.CAR_CONTROL_COMMAND_ID_GET_DEVICE_INFO:
                if (isConnecting) {
                    CarControlSettings.initGuiResource();
                    connectParam = Constant.ConnectParam.GETDEVICEPASSWORD;
                    doGetWifiPassword();
//                        Message msg = new Message();
//                        msg.what = MSG_CONNECT_ERROR;
//                        msg.obj = "401";
//                        handler.sendMessage(msg);


                }
                break;

            case CarControlCommand.CAR_CONTROL_COMMAND_GET_WIFI_PASSWORD:
                if (isConnecting) {
                    if (info.rval == 0 && info.param != null) {
                        MyApplication.wifiPassword = info.param;
                        AoniRecorderInfoUtils.modifyConnectedRecorderInfo(MyApplication.wifiSSID, "wifiPassword", MyApplication.wifiPassword);
                        connectParam = Constant.ConnectParam.GETDEVICESETTING;
                        doGetAllSettings();
                    } else {
                        Message msg = new Message();
                        msg.what = MSG_CONNECT_ERROR;
                        msg.obj = "402";
                        handler.sendMessage(msg);
                    }
                }
                break;

            case CarControlCommand.CAR_CONTROL_COMMAND_ID_GET_ALL_SETTINGS:
                if (isConnecting) {
                    if (info.rval == 0 && info.param != null) {
                        CarControlSettings.parseAllSettings(info.param);
                        setTime();
                        stopConnectAnimation();
                        startActivityOfTime();
                        addSetting();
                        AoniRecorderInfoUtils.saveConnectedRecorderInfo(MyApplication.wifiSSID, MyApplication.wifiPassword, CarControl.DeviceInfo.model);
                        EventBus.getDefault().post(new ScreenDisplayEvent());

                    } else {
                        Message msg = new Message();
                        msg.what = MSG_CONNECT_ERROR;
                        msg.obj = "403";
                        handler.sendMessage(msg);

                    }
                }

                break;


        }
    }


    private void setTime() {
        SpUtils.putBoolean(Constant.SpKeyParam.IS_SETT_TIME_OF_MANUAL, false);
        CarControlSettings.SettingItem settingItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_TIME);
        if (settingItem != null && null != settingItem.settingItemValue && CarSettingGuiHandler.SETTING_ITEM_TIME_OPTION_AUTO.equals(settingItem.settingItemValue)) {
            CarControl.doSetSettingItemValue(settingItem.settingItemKey, CarSettingGuiHandler.SETTING_ITEM_TIME_OPTION_AUTO + "," + DateUtils.getDate(new Date(), true, true, true, true, DateUtils.FORMAT_ONE, true).replace(" ", "_"), null);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkNetworkAvailable() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || SocketUtils.wifiNetwork != null) {
            return;
        }
        try {
            NetworkRequest localNetworkRequest = new NetworkRequest.Builder().removeCapability(NET_CAPABILITY_INTERNET).addTransportType(TRANSPORT_WIFI).build();
            ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    try {
                        SocketUtils.setWifiNetwork(network);
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            ConnectivityManager.setProcessDefaultNetwork(network);
                        }
                    } catch (Exception ex) {
                    }
                }

                @Override
                public void onLost(Network network) {
                    super.onLost(network);
                    SocketUtils.setWifiNetwork(null);
                }

            };
            connectivityManager.requestNetwork(localNetworkRequest, networkCallback);
        } catch (Exception e) {
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void forceSendRequestByMobileData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                NetworkRequest.Builder builder = new NetworkRequest.Builder();
                builder.addCapability(NET_CAPABILITY_INTERNET);
                builder.addTransportType(TRANSPORT_CELLULAR);
                NetworkRequest networkRequest = builder.build();
                ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        SocketUtils.setMobileNetWork(network);
                        if (Build.VERSION.SDK_INT >= 23) {
                            connectivityManager.bindProcessToNetwork(network);
                        } else {
                            // 23后这个方法舍弃了
                            ConnectivityManager.setProcessDefaultNetwork(network);
                        }
                    }

                    @Override
                    public void onLost(Network network) {
                        super.onLost(network);
                        SocketUtils.setMobileNetWork(null);
                        connectivityManager.unregisterNetworkCallback(this);

                    }
                };
                connectivityManager.requestNetwork(networkRequest, networkCallback);
            } catch (Exception e) {

            }
        }
    }

    private void enterRecorder() {
        startConnectAnimation();
        delayEnterRecorder();
    }

    private void delayEnterRecorder() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (CarControl.IsConnected.get()) {
                  int settingSize =   CarControlSettings.getAllSettingItems().size();
                  if (settingSize>0){
                      stopConnectAnimation();
                      startActivityOfTime();
                  }else{
                      if (isConnecting) {
                          handler.sendEmptyMessage(MSG_GET_DEVICE_INFO_ERROR);
                      }
                  }
                } else {
                    timeOutCode = 500;
                    CarControl.HeartBeatStart(MyApplication.IP, ParamManager.CarServerParam.CarControlNotifyPort, "hi", "aoni");
                }
            }
        }, 800);
    }


    private void stopConnectAnimation() {
        timeOut = 0;
        isConnecting = false;
        handler.removeMessages(MSG_CONNECT_TIME_OUT);
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (null != progressTv) {
                    progressTv.clearAnimation();
                    progressTv.setVisibility(View.GONE);
                }
                setConnectBtnEnable(true);
            }
        });

    }

    private static final int MIN_DELAY_TIME = 2000;  // 两次间隔不能少于2000ms
    private static long lastClickTime;

    public void startActivityOfTime() {
        long currentClickTime = System.currentTimeMillis();
        if (!isTimeOut && (currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            lastClickTime = currentClickTime;
            ActivityUtils.jumpActivity(getActivity(), RecorderActivity.class);
        }

    }


    public void addSetting() {
        addSystemSetting();
        addRecorderMsgSetting();
        addWifiSetting();
    }

    private void addSystemSetting() {
        CarControlSettings.SettingItem s2 = new CarControlSettings.SettingItem();
        s2.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_RESTORE_FACTORY_SETTINGS;
        CarControlSettings.getAllSettingItems().add(s2);
    }

    private void addRecorderMsgSetting() {
        CarControlSettings.SettingItem s6 = new CarControlSettings.SettingItem();
        s6.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_FORMAT_SD_CARD;
        CarControlSettings.SettingItem s = new CarControlSettings.SettingItem();
        s.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_FW_VERSION;
        s.settingItemValue = CarControl.DeviceInfo.fw_version;

        CarControlSettings.SettingItem s3 = new CarControlSettings.SettingItem();
        s3.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_SD_CARD_SIZE;
        s3.settingItemValue = "";
        CarControlSettings.SettingItem s5 = new CarControlSettings.SettingItem();
        s5.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_APP_VERSION;
        try {
            s5.settingItemValue = "V " + getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        CarControlSettings.getAllSettingItems().add(s3);
        CarControlSettings.getAllSettingItems().add(s6);
        CarControlSettings.getAllSettingItems().add(s);
        CarControlSettings.getAllSettingItems().add(s5);
    }

    private void addWifiSetting() {
        CarControlSettings.SettingItem s = new CarControlSettings.SettingItem();
        s.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_WIFI_PASSWORD_MODIFY;
        s.settingItemValue = "";
        CarControlSettings.getAllSettingItems().add(s);
    }

}

